#include "prosetpage.h"
#include "ui_prosetpage.h"

#include <QLineEdit>
#include <QDir>
#include <QDebug>
#include <QFileDialog>

ProSetPage::ProSetPage(QWidget *parent)
    : QWizardPage(parent)
    , ui(new Ui::ProSetPage)
{
    ui->setupUi(this);

    registerField("proPath", ui->lineEdit_2);
    registerField("proName*", ui->lineEdit);

    // completeChanged 是继承基类 QWizardPage 来的
    // completeChanged 信号发出后会触发 QWizardPage 类的 isComplete 函数
    connect(ui->lineEdit, &QLineEdit::textEdited, this, &ProSetPage::completeChanged);
    connect(ui->lineEdit_2, &QLineEdit::textEdited, this, &ProSetPage::completeChanged);
    QString curPath = QDir::currentPath();
    ui->lineEdit_2->setText(curPath);
    ui->lineEdit_2->setCursorPosition(ui->lineEdit_2->text().size());
    ui->lineEdit->setClearButtonEnabled(this);
    ui->lineEdit_2->setClearButtonEnabled(this);
}

ProSetPage::~ProSetPage()
{
    delete ui;
}

// 把两个 QLineEdit 的内容返回给 QWizard 页面
void ProSetPage::GetProSettings(QString &name, QString &path)
{
    name = ui->lineEdit->text();
    path = ui->lineEdit_2->text();
}

// completeChanged 信号发出后会触发 QWizardPage 类的 isComplete 函数
bool ProSetPage::isComplete() const{
    if(ui->lineEdit->text() == "" || ui->lineEdit_2->text() == ""){
        return false;
    }

    // 先判断输入的（path）打开的文件夹，是否存在
    QDir dir(ui->lineEdit_2->text());
    if(dir.exists() == false){
        // qDebug() << "file path is not exists" << Qt::endl;
        ui->tips->setText("project has exists");
        return false;
    }

    // 再结合输入的 name，判断整个路径是否存在
    // 下面一行的功能是：把 ui->lineEdit->text() 拼接到 ui->lineEdit_2->text() 后面形成一个完整的路径
    QString absFilePath = dir.absoluteFilePath(ui->lineEdit->text());
    // qDebug() << "absFilePath is " << absFilePath << Qt::endl;
    QDir dist_dir(absFilePath);
    if(dist_dir.exists() == true){
        ui->tips->setText("project has exists, change path or name!");
        return false;
    }

    ui->tips->setText("");
    return QWizardPage::isComplete(); // 继续调用基类的虚函数
}

// 添加浏览按钮点击后选择文件夹的操作
void ProSetPage::on_browse_clicked()
{
    QFileDialog file_dialog;
    file_dialog.setFileMode(QFileDialog::Directory); // 打开目录
    file_dialog.setWindowTitle("选择导入的文件夹");
    auto path = QDir::currentPath();
    file_dialog.setDirectory(path);
    file_dialog.setViewMode(QFileDialog::Detail);

    QStringList fileNames;
    if(file_dialog.exec()){
        fileNames = file_dialog.selectedFiles();
    }

    if(fileNames.length() <= 0){
        return;
    }

    QString import_path = fileNames.at(0);
    qDebug() << "import_path is " << import_path << Qt::endl;
    ui->lineEdit_2->setText(import_path);
}

